package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.service.api.AuthService;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import entity.Auth;
import entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
public class AssignHandler {
    @Autowired
   private RoleService roleService;
    @Autowired
   private AdminService adminService;
@Autowired
private  AuthService authService;

    @RequestMapping("assign/do/assign.html")
    public String saveAdminRoleRelationship(
            @RequestParam("adminId") Integer adminId,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("keyword") String keyword,
            @RequestParam(value = "roleIdList", required = false) List<Integer> roleIdList
    ){

        adminService.saveAdminRoleRelationship(adminId, roleIdList);

        //重定向（减少数据库操作）返回信息页
        return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }

    @ResponseBody
    @RequestMapping("/assign/get/tree.json")
    public ResultEntity<List<Auth>> getAuthTree(){
        List<Auth> authList = authService.queryAuthList();

        return ResultEntity.successWthData(authList);
    }

    @RequestMapping("assign/to/assign/role/page.html")
    public String toAssignRolePage(@RequestParam("adminId") Integer adminId,
                                         ModelMap modelMap){
    //1. 查询已经分配的角色
        List<Role> assignedRoleList= roleService.getAssignedRole(adminId);
        //2. 查询没有分配的角色
        List<Role> unAssignedRole = roleService.getUnAssignedRole(adminId);
        //3. 存入模型
        modelMap.addAttribute("assignedRoleList",assignedRoleList);
        modelMap.addAttribute("unAssignedRoleList",unAssignedRole);
        return "assign-role";
    }
    // 获得被勾选的auth信息
    @ResponseBody
    @RequestMapping("/assign/get/checked/auth/id.json")
    public ResultEntity<List<Integer>> getAuthByRoleId(Integer roleId){
        List<Integer> authIdList = authService.getAuthByRoleId(roleId);
        return ResultEntity.successWthData(authIdList);
    }
    @ResponseBody
    @RequestMapping("/assign/do/save/role/auth/relationship.json")
    public ResultEntity<String> saveRoleAuthRelationship(
            @RequestBody Map<String,List<Integer>> map ) {

        authService.saveRoleAuthRelationship(map);
        return ResultEntity.successWthoutData();
    }

}
